using System;
using System.Configuration;
using CodePlex.TfsLibrary;

namespace CodePlex.CodePlexClientLibrary
{
    public abstract class AppConfigBase : IAppConfig
    {
        public virtual string AnonymousUsername
        {
            get { return null; }
        }

        public virtual bool AttemptAutoMerge // Temporary setting until we bring our diff/merge engines online
        {
            get { return ParseBool(GetSetting("AttemptAutoMerge"), false); }
        }

        public abstract string CodePlexWebServiceUrl { get; }

        public virtual bool DefaultToGuiForCommit
        {
            get { return ParseBool(GetSetting("DefaultToGuiForCommit"), false); }
        }

        public virtual bool DefaultToGuiForStatus
        {
            get { return ParseBool(GetSetting("DefaultToGuiForStatus"), false); }
        }

        public virtual string DiffArgs
        {
            get { return GetSetting("DiffArgs"); }
        }

        public virtual string DiffTool
        {
            get { return GetSetting("DiffTool"); }
        }

        public virtual string Editor
        {
            get { return GetSetting("Editor") ?? GetEnv("EDITOR") ?? GetEnv("VISUAL") ?? "notepad.exe"; }
        }

        protected abstract string EnvironmentPrefix { get; }

        public virtual bool ForceBasicAuth
        {
            get { return ParseBool(GetSetting("ForceBasicAuth"), false); }
        }

        public virtual string IgnoreFile
        {
            get { return GetSetting("IgnoreFile") ?? ".tfs-ignore"; }
        }

        public virtual string MergeArgs
        {
            get { return GetSetting("MergeArgs"); }
        }

        public virtual string MergeTool
        {
            get { return GetSetting("MergeTool"); }
        }

        public abstract bool TryDefaultCredentials { get; }

        protected static string GetEnv(string environmentVariableName)
        {
            return Environment.GetEnvironmentVariable(environmentVariableName);
        }

        protected string GetSetting(string appSettingName)
        {
            return GetEnv(EnvironmentPrefix + appSettingName) ?? ConfigurationManager.AppSettings[appSettingName];
        }

        protected static bool ParseBool(string value,
                                        bool defaultValue)
        {
            bool result;
            return bool.TryParse(value, out result) ? result : defaultValue;
        }
    }
}